package repository

import (
	"RocFamilySystem/models"
	"fmt"
	"gorm.io/gorm"
)

type HardwareDriverRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["HardwareDriverRepository"] = &HardwareDriverRepository{}
}

func (r *HardwareDriverRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertHardwareDriver 添加硬件设备
func (r *HardwareDriverRepository) InsertHardwareDriver(hardwareDriver *models.HardwareDriver) {
	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Create(hardwareDriver).Error
	handleRepositoryErr(err, "添加硬件设备失败")
}

// DeleteHardwareDriver 删除硬件设备
func (r *HardwareDriverRepository) DeleteHardwareDriver(hardwareDriverId int) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Delete(&models.HardwareDriver{Id: &hardwareDriverId}).Error
	handleRepositoryErr(err, "删除硬件设备失败")
}

// UpdateHardwareDriver 修改硬件设备
func (r *HardwareDriverRepository) UpdateHardwareDriver(hardwareDriver *models.HardwareDriver) {
	err := r.Db.Model(hardwareDriver).Omit("id", "create_time").Updates(hardwareDriver).Error
	handleRepositoryErr(err, "修改硬件设备失败")
}

// SelectHardwareDriver 查询硬件设备
func (r *HardwareDriverRepository) SelectHardwareDriver(hardwareDriver *models.HardwareDriver, pageNum, pageSize int) ([]models.HardwareDriver, int) {
	var (
		list  []models.HardwareDriver
		total int64
	)
	db := r.Db.Model(&models.HardwareDriver{})

	if hardwareDriver != nil {
		if hardwareDriver.CreateBy != nil {
			db = db.Where("create_by = ?", *hardwareDriver.CreateBy)
		}
		if hardwareDriver.Remark != nil {
			db = db.Where("remark like ?", fmt.Sprintf("%%%s%%", *hardwareDriver.Remark))
		}
	}

	//获取总数
	db.Count(&total)

	//获取列表
	db.Offset(pageSize * pageNum).Limit(pageSize)
	db.Find(&list)

	return list, int(total)
}

// SelectHardwareDriverById 查询硬件设备通过ID
func (r *HardwareDriverRepository) SelectHardwareDriverById(id int) models.HardwareDriver {
	var hardwareDriver models.HardwareDriver
	err := r.Db.First(&hardwareDriver, "id = ?", id).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return hardwareDriver
}

// SelectHardwareDriverByIds 查询硬件设备通过Ids
func (r *HardwareDriverRepository) SelectHardwareDriverByIds(ids []string) []models.HardwareDriver {
	var hardwareDriverList []models.HardwareDriver
	err := r.Db.Find(&hardwareDriverList, "id in (?)", ids).Error
	if err != nil {
		handleRepositoryErr(err, "查询失败")
	}
	return hardwareDriverList
}

// DeleteHardwareDriverBatch 批量删除硬件设备
func (r *HardwareDriverRepository) DeleteHardwareDriverBatch(ids []string) {
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Where("id in (?)", ids).Delete(models.HardwareDriver{}).Error
	handleRepositoryErr(err, "删除硬件设备失败！")
}

// InsertHardwareDriverBatch 批量添加硬件设备
func (r *HardwareDriverRepository) InsertHardwareDriverBatch(list []models.HardwareDriver) {
	//开启事务
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Create(&list).Error
	handleRepositoryErr(err, "批量添加硬件设备失败")
}
